package org.bookie.web.pages.admin;

import org.apache.tapestry.IExternalPage;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.annotations.InjectObject;
import org.apache.tapestry.annotations.Persist;
import org.bookie.framework.CommonBasePage;
import org.bookie.model.Bet;
import org.bookie.model.Outcome;
import org.bookie.model.Role;
import org.bookie.model.security.Access;
import org.bookie.model.services.BetDAO;
import org.bookie.model.services.OutcomeDAO;

@Access(role = Role.ADMIN)
public abstract class EditBet extends CommonBasePage implements IExternalPage{

	public void activateExternalPage(Object[] parameters, IRequestCycle cycle) {
		if (parameters.length != 1) {
			throw new RuntimeException("Need one Long parameter event ID");
		}
		setBetId((Long) parameters[0]);
	}

	/**
	 * Adds a new outcome.
	 */
	public void doAddOutcome() {
		if (getDelegate().getHasErrors()) {
			return;
		}
		Outcome outcome = new Outcome(getOutcomeLabel(), getOutcomeOdds());
		if (getBet().getId() != null) {
			getBet().addOutcome(outcome);
			setMessage(getMessages().getMessage("admin.edit.bet.msg.outcome.added"));
		}
		setOutcomeLabel(null);
		setOutcomeOdds(null);
	}

	/**
	 * Deletes outcome
	 * 
	 * @param outcomeId
	 * @return
	 */
	public void doDeleteOutcome(Long outcomeId) {
		Outcome outcome = getOutcomeDAO().findById(outcomeId);
		if (outcome != null) {
			getBet().getOutcomes().remove(outcome);
			getOutcomeDAO().makeTransient(outcome);
		}
		setMessage(getMessages().format("admin.edit.bet.msg.outcome.deleted", outcome.getLabel()));
	}

	public void doSave() {
		if (getDelegate().getHasErrors()) {
			return;
		}
		setMessage(getMessages().getMessage("admin.edit.bet.msg.updated"));
	}

	public Bet getBet() {
		return getBetDAO().findById(getBetId());
	}

	/**
	 * Injected {@link BetDAO} service.
	 * 
	 * @return instance of BetDAO
	 */
	@InjectObject("service:bookie.model.BetDAO")
	public abstract BetDAO getBetDAO();

	/**
	 * Injected {@link OutcomeDAO} service.
	 * 
	 * @return instance of OutcomeDAO
	 */
	@InjectObject("service:bookie.model.OutcomeDAO")
	public abstract OutcomeDAO getOutcomeDAO();

	@Persist
	public abstract Long getBetId();
	public abstract void setBetId(Long value);
	
	public abstract String getOutcomeLabel();
	public abstract void setOutcomeLabel(String label);
	public abstract Double getOutcomeOdds();
	public abstract void setOutcomeOdds(Double odds);
}
